<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-title">
				客服名称：{{ toName }}
			</view>
			<view class="navbar-right" v-show="isOnline">
				在线
			</view>
			<view class="navbar-right" v-show="!isOnline">
				离线
			</view>
		</view>
		<!-- 聊天内容 -->
		<scroll-view class="chat-content" scroll-y :scroll-into-view="scrollIntoView">
			<view v-for="(msg, index) in messages" :key="index" :class="['chat-item', directionClass(msg.direction)]">
				<view v-if="msg.direction === 1" class="message customer">
					<u-avatar class="avatar" src="/static/customer-avatar.png"></u-avatar>
					<view class="message-content">
						<view class="text">{{ msg.content }}</view>
						<view class="time">{{ msg.time }}</view>
					</view>
				</view>
				<view v-else-if="msg.direction === 2" class="message user">
					<u-avatar class="avatar user-avatar" src="/static/user-avatar.png"></u-avatar>
					<view class="message-content">
						<view class="text">{{ msg.content }}</view>
						<view class="time">{{ msg.time }}</view>
					</view>
				</view>
				<view v-else-if="msg.direction === 0" class="message system">
					<view class="system-message">{{ msg.content }}</view>
				</view>
			</view>
			<view id="bottom" />
		</scroll-view>

		<!-- 星级评分 -->
		<view class="rating-section">
			<u-rate v-model="rating" :max="5" inactive-color="#ccc" active-color="#ffd700" />
			<view style="margin-left: auto;">
				<u-button class="end-service-button" @click="endService">结束服务</u-button>
			</view>
		</view>
		<!-- 聊天栏 -->
		<up-tabbar activeColor="#6bc493">

			<!-- 输入框和发送按钮 -->
			<view class="input-section">
				<u-input v-model="sendMessage.message" placeholder="输入消息..." class="chat-input" />
				<u-button type="primary" @click="submit" class="send-button">发送</u-button>
			</view>
		</up-tabbar>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick,
		onMounted,
	} from 'vue';
	
	import { useUserStore } from '@/stores/user.js'
	import { getAgentMsg, sendAgentMsg } from "@/common/api.js"
	
	const webSocket = ref()
	const userStore = useUserStore().user
	
	const chatMes = ref(false)
	const isOnline = ref(true)
	const username = ref('')
	const toName = ref('')
	const sendMessage = ref({
	  toUserId: userStore.userId,
	  message: '',
	  direction: 1
	})
	const rating = ref(5); // 评分数据
	const scrollIntoView = ref('');
	const messages = ref([]);
	
	onMounted(() => {
	  console.log("userStore:", userStore.userId) 
	  username.value = userStore.userId
	  init()
	})
	
	const init = async () => {
	
	  // 创建 WebSocket 对象
	  webSocket.value = new WebSocket('ws://localhost:7024/chat/' + userStore.userId + '/' + 1)
	
	  webSocket.value.onopen = onOpen
	
	  // 接收到服务端推送的消息后触发
	  webSocket.value.onmessage = onMessage
	
	  webSocket.value.onclose = onClose
	}
	
	
	const onOpen = () => {
	  isOnline.value = true
	   getAgentMsg({
	        userId: userStore.userId,
	      }).then((res)=>{
	        console.log("登录的用户：", userStore.userId)
	        console.log("获取到的历史消息：", res.data)
	        // 清除聊天区的数据
	        messages.value = [{
				direction: 0,
				content: '系统消息：欢迎使用客服系统！',
				time: new Date().toLocaleTimeString()
			},{
				direction: 0,
				content: '系统消息：欢迎使用客服系统！',
				time: new Date().toLocaleTimeString()
			},]
			for (let item of res.data) {
				messages.value.push({
					direction: item.direction,
					content: item.message,
					time: new Date(item.createTime).toLocaleTimeString(),
				})
			}
	        // 显示正在和谁聊天
	        chatMes.value = true
	      })
	}

	const onClose = () => {
	  isOnline.value = false
	}
	
	const onMessage = (event) => {
	  // 获取服务端推送过来的消息
	  let dataString = event.data
	  // 将 dataString 转换为 json 对象
	  let response = JSON.parse(dataString)
	
	  console.log('服务端推送过来的消息：', response)
	
	
	  if (response.isSystem) {
	    if (response.type == 1){
	      toName.value = response.data
	    }
	    messages.value.push({
			content: response.message,
			direction: 0,
			time: new Date().toLocaleTimeString()
		})
	  } else {
	    // 非系统消息
	    messages.value.push({
	      userId: toName.value,
	      content: response.message,
	      direction: 2,
		  time: new Date().toLocaleTimeString()
	    })
	  }
	  
	  // 等待 DOM 更新后滚动到最底部
	  nextTick(() => {
	  	scrollIntoView.value = 'bottom';
	  });
	}
	
	const submit = () => {
		sendMessage.value.message = sendMessage.value.message.trim()

		if (!sendMessage.value.message) {
			console.log('请输入聊天内容')
			return
		}
		messages.value.toUserId = toName.value
	  
		console.log(messages.value)
		messages.value.push({
		  userId: sendMessage.value.toUserId,
		  content: sendMessage.value.message,
		  direction: 2,
		  time: new Date().toLocaleTimeString()
		})
		console.log("此时的消息记录：", messages.value)
		// 记录进聊天信息
		sendAgentMsg({
			toUserId: userStore.userId,
			message: sendMessage.value.message,
			direction: 1
		})
		 .then((response) => {
			console.log('发送消息接口-后台返回的数据：', response)
		})

		webSocket.value.send(JSON.stringify(sendMessage.value));
		sendMessage.value.message = ''
		
		// 等待 DOM 更新后滚动到最底部
		nextTick(() => {
			scrollIntoView.value = 'bottom';
		});
	}

	// 处理结束服务
	const endService = () => {
		console.log(`用户评分：${rating.value} 星`);
		// 可以添加其他结束服务的逻辑，例如关闭会话等
		messages.value.push({
			content: "成功结束服务，已为客服评分" + rating.value + "星",
			direction: 0,
			time: new Date().toLocaleTimeString()
		})
		const tmp = {
			direction:3,
			content:rating.value
		}
		webSocket.value.send(JSON.stringify(tmp));
		// 等待 DOM 更新后滚动到最底部
		nextTick(() => {
			scrollIntoView.value = 'bottom';
		});
	};

	// 获取消息方向对应的类名
	const directionClass = (direction) => {
		if (direction === 1) return 'customer';
		if (direction === 2) return 'user';
		return 'system';
	};
	
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.custom-navbar {
		width: 100%;
		height: 50px;
		/* 根据需要调整高度 */
		background-color: #007BFF;
		/* 示例背景颜色 */
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		color: white;
		position: fixed;
		/* 固定在页面顶部 */
		/* top: 0; */
		/* 距离页面顶部0 */
		/* left: 0; */
		/* 距离页面左侧0 */
		z-index: 999;
		/* 确保导航栏在最上层 */
	}

	.navbar-title {
		font-weight: bold;
	}

	.navbar-right {
		margin-right: 50px;
		text-align: right;
	}

	.content {
		margin-top: 60px;
		/* 留出足够空间避免被导航栏遮挡 */
		padding: 10px;
	}


	.chat-content {
		flex: 1;
		padding: 10px;
		background-color: #f5f5f5;
		overflow-y: auto;
	}

	.chat-item {
		display: flex;
		margin-bottom: 10px;
	}

	.customer {
		flex-direction: row;
		align-items: flex-start;
	}

	.user {
		flex-direction: row-reverse;
		align-items: flex-start;
	}

	.system {
		justify-content: center;
		text-align: center;
		width: 100%;
	}

	.avatar {
		width: 30px;
		height: 30px;
		margin-right: 10px;
	}

	.user-avatar {
		margin-left: 110px;
	}

	.message-content {
		max-width: 80%;
		padding: 10px;
		border-radius: 8px;
		background-color: #fff;
		box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
	}

	.system-message {
		background-color: #f0f0f0;
		color: #555;
		padding: 10px;
		border-radius: 8px;
	}

	.text {
		font-size: 14px;
		color: #333;
	}

	.time {
		font-size: 12px;
		color: #aaa;
		margin-top: 5px;
	}

	.chat-bar {
		padding: 10px;
		background-color: #fff;
		border-top: 1px solid #eee;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
	}

	.rating-section {
		padding: 10px;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.end-service-button {
		background-color: #87cefa;
		color: #fff;
		padding: 5px 10px;
		font-size: 14px;
		width: 80px;
		margin-left: auto;
	}

	.input-section {
		display: flex;
		align-items: center;
		padding: 10px;
	}

	.chat-input {
		flex: 1;
		width: 400px;
		margin-right: 10px;
		border-radius: 50px;
	}

	.send-button {
		width: 50px;
		background-color: #87cefa;
		color: #fff;
		padding: 5px 15px;
		font-size: 14px;
	}

	.u-tabbar[data-v-d5be2d5d] {
		flex: 0;
	}
</style>